<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import {
  Card,
  Table,
  Button,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  Space,
  Tag,
  message,
} from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue/es/form';

import {
  createLandingCompanyApi,
  getLandingCompaniesApi,
  updateLandingCompanyApi,
  type LandingCompanyApi,
} from '#/api/core';

const loading = ref(false);
const saving = ref(false);
const companies = ref<LandingCompanyApi.LandingCompanyRecord[]>([]);
const isModalVisible = ref(false);
const isEditing = ref(false);
const currentId = ref<number | null>(null);
const formRef = ref<FormInstance>();

const ensureBillingCategories = (value: string[] | undefined | null) =>
  Array.isArray(value)
    ? value
        .map((item) => (typeof item === 'string' ? item.trim() : ''))
        .filter((item) => item.length > 0)
    : [];

const validateBillingCategories = (_rule: unknown, value: string[]) => {
  const sanitized = ensureBillingCategories(value);
  return sanitized.length
    ? Promise.resolve()
    : Promise.reject(new Error('请至少填写一个开票类目'));
};

const formState = reactive({
  name: '',
  short_name: '',
  code: '',
  tax_number: '',
  address: '',
  contact_person: '',
  phone: '',
  email: '',
  status: 'active' as LandingCompanyApi.LandingCompanyStatus,
  billing_categories: [] as string[],
  remark: '',
  bank_name: '',
  account_number: '',
  balance: 0,
});

const columns: TableColumnsType<LandingCompanyApi.LandingCompanyRecord> = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 70 },
  { title: '名称', dataIndex: 'name', key: 'name', width: 180 },
  { title: '简称', dataIndex: 'short_name', key: 'short_name', width: 120 },
  { title: '代码', dataIndex: 'code', key: 'code', width: 120 },
  { title: '税号', dataIndex: 'tax_number', key: 'tax_number', width: 150 },
  { title: '联系人', dataIndex: 'contact_person', key: 'contact_person', width: 120 },
  { title: '电话', dataIndex: 'phone', key: 'phone', width: 140 },
  { title: '邮箱', dataIndex: 'email', key: 'email', width: 200 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '开户行', dataIndex: 'bank_name', key: 'bank_name', width: 180 },
  { title: '银行账号', dataIndex: 'account_number', key: 'account_number', width: 200 },
  { title: '账号余额', dataIndex: 'balance', key: 'balance', width: 140 },
  { title: '开票类目', dataIndex: 'billing_categories', key: 'billing_categories', width: 200 },
  { title: '地址', dataIndex: 'address', key: 'address', width: 220 },
  { title: '备注', dataIndex: 'remark', key: 'remark', width: 220 },
  { title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 180 },
  { title: '更新时间', dataIndex: 'updated_at', key: 'updated_at', width: 180 },
  { title: '操作', key: 'actions', fixed: 'right', width: 120 },
];

const formatBalance = (value: number) =>
  new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(
    Number(value || 0),
  );

const fetchCompanies = async () => {
  loading.value = true;
  try {
    const response = await getLandingCompaniesApi();
    companies.value = response?.items ?? [];
  } catch (error) {
    console.error('获取落地公司列表失败', error);
    message.error('获取落地公司列表失败');
  } finally {
    loading.value = false;
  }
};

const resetForm = () => {
  formState.name = '';
  formState.short_name = '';
  formState.code = '';
  formState.tax_number = '';
  formState.address = '';
  formState.contact_person = '';
  formState.phone = '';
  formState.email = '';
  formState.status = 'active';
  formState.billing_categories = [];
  formState.remark = '';
  formState.bank_name = '';
  formState.account_number = '';
  formState.balance = 0;
};

const openCreateModal = () => {
  isEditing.value = false;
  currentId.value = null;
  resetForm();
  formRef.value?.resetFields();
  isModalVisible.value = true;
};

const openEditModal = (record: LandingCompanyApi.LandingCompanyRecord) => {
  isEditing.value = true;
  currentId.value = record.id;
  formState.name = record.name;
  formState.short_name = record.short_name;
  formState.code = record.code;
  formState.tax_number = record.tax_number;
  formState.address = record.address;
  formState.contact_person = record.contact_person;
  formState.phone = record.phone;
  formState.email = record.email;
  formState.status = record.status;
  formState.billing_categories = ensureBillingCategories(record.billing_categories);
  formState.remark = record.remark;
  formState.bank_name = record.bank_name;
  formState.account_number = record.account_number;
  formState.balance = Number(record.balance || 0);
  formRef.value?.clearValidate?.();
  isModalVisible.value = true;
};

const handleModalCancel = () => {
  isModalVisible.value = false;
  formRef.value?.resetFields();
  saving.value = false;
};

const submitForm = async () => {
  try {
    const values = await formRef.value?.validate();
    if (!values) return;

    const payload: LandingCompanyApi.UpsertLandingCompanyPayload = {
      ...values,
      billing_categories: ensureBillingCategories(values.billing_categories),
      balance: Number(values.balance ?? 0),
    };

    saving.value = true;
    if (isEditing.value && currentId.value) {
      await updateLandingCompanyApi(currentId.value, payload);
      message.success('落地公司信息已更新');
    } else {
      await createLandingCompanyApi(payload);
      message.success('落地公司创建成功');
    }

    isModalVisible.value = false;
    await fetchCompanies();
  } catch (error: any) {
    if (error?.errorFields) {
      return;
    }
    console.error('保存落地公司失败', error);
    message.error('保存落地公司失败');
  } finally {
    saving.value = false;
  }
};

onMounted(() => {
  fetchCompanies();
});
</script>

<template>
  <div class="p-5">
    <Card title="落地公司管理" :bordered="false" class="mb-4">
      <template #extra>
        <Button type="primary" @click="openCreateModal">新增落地公司</Button>
      </template>

      <Table
        :columns="columns"
        :data-source="companies"
        :loading="loading"
        row-key="id"
        :pagination="{ pageSize: 10 }"
        :scroll="{ x: 1600 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <Tag :color="record.status === 'active' ? 'green' : 'gold'">
              {{ record.status === 'active' ? '启用' : '禁用' }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'balance'">
            ¥{{ formatBalance(record.balance) }}
          </template>
          <template v-else-if="column.key === 'billing_categories'">
            {{ (record.billing_categories || []).join('、') || '--' }}
          </template>
          <template v-else-if="column.key === 'actions'">
            <Space>
              <Button type="link" @click="openEditModal(record)">编辑</Button>
            </Space>
          </template>
          <template v-else>
            {{ (record as any)[column.dataIndex as string] ?? '--' }}
          </template>
        </template>
      </Table>
    </Card>

    <Modal
      v-model:open="isModalVisible"
      :title="isEditing ? '编辑落地公司' : '新增落地公司'"
      :confirm-loading="saving"
      @ok="submitForm"
      @cancel="handleModalCancel"
    >
      <Form ref="formRef" :model="formState" layout="vertical">
        <Form.Item label="公司名称" name="name" :rules="[{ required: true, message: '请输入公司名称' }]">
          <Input v-model:value="formState.name" placeholder="请输入公司名称" />
        </Form.Item>
        <Form.Item label="公司简称" name="short_name" :rules="[{ required: true, message: '请输入公司简称' }]">
          <Input v-model:value="formState.short_name" placeholder="请输入公司简称" />
        </Form.Item>
        <Form.Item label="公司代码" name="code" :rules="[{ required: true, message: '请输入公司代码' }]">
          <Input v-model:value="formState.code" placeholder="请输入公司代码" />
        </Form.Item>
        <Form.Item label="税号" name="tax_number" :rules="[{ required: true, message: '请输入税号' }]">
          <Input v-model:value="formState.tax_number" placeholder="请输入税号" />
        </Form.Item>
        <Form.Item label="公司地址" name="address" :rules="[{ required: true, message: '请输入公司地址' }]">
          <Input v-model:value="formState.address" placeholder="请输入公司地址" />
        </Form.Item>
        <Form.Item label="联系人" name="contact_person" :rules="[{ required: true, message: '请输入联系人' }]">
          <Input v-model:value="formState.contact_person" placeholder="请输入联系人" />
        </Form.Item>
        <Form.Item label="联系电话" name="phone" :rules="[{ required: true, message: '请输入联系电话' }]">
          <Input v-model:value="formState.phone" placeholder="请输入联系电话" />
        </Form.Item>
        <Form.Item label="联系邮箱" name="email" :rules="[{ required: true, type: 'email', message: '请输入有效的邮箱' }]">
          <Input v-model:value="formState.email" placeholder="请输入联系邮箱" />
        </Form.Item>
        <Form.Item label="状态" name="status" :rules="[{ required: true, message: '请选择状态' }]">
          <Select v-model:value="formState.status">
            <Select.Option value="active">启用</Select.Option>
            <Select.Option value="inactive">禁用</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item
          label="开票类目"
          name="billing_categories"
          :rules="[{ validator: validateBillingCategories }]"
        >
          <Select
            v-model:value="formState.billing_categories"
            mode="tags"
            allow-clear
            placeholder="输入后回车添加多个类目"
          />
        </Form.Item>
        <Form.Item label="备注" name="remark" :rules="[{ required: true, message: '请输入备注信息' }]">
          <Input.TextArea v-model:value="formState.remark" placeholder="请输入备注信息" :rows="3" />
        </Form.Item>
        <Form.Item label="开户行" name="bank_name" :rules="[{ required: true, message: '请输入开户行' }]">
          <Input v-model:value="formState.bank_name" placeholder="请输入开户行" />
        </Form.Item>
        <Form.Item label="银行账号" name="account_number" :rules="[{ required: true, message: '请输入银行账号' }]">
          <Input v-model:value="formState.account_number" placeholder="请输入银行账号" />
        </Form.Item>
        <Form.Item label="账号余额" name="balance" :rules="[{ required: true, message: '请输入账号余额' }]">
          <InputNumber
            v-model:value="formState.balance"
            :min="0"
            :step="0.01"
            style="width: 100%"
            placeholder="请输入账号余额"
          />
        </Form.Item>
      </Form>
    </Modal>
  </div>
</template>
